package org.example.supplychain.controller;

import jakarta.servlet.http.HttpSession;
import org.example.supplychain.domain.Supplier;
import org.example.supplychain.service.OrderService;
import org.example.supplychain.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.stream.Stream;

@Controller
@RequestMapping("/supplier")
public class SupplierController {
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private OrderService orderService;
    
    @PostMapping("/query")
    public String query(@RequestParam("supplierName") String supplierName, Model model){
        supplierService.calculateSupplierMark();
        List<Supplier> list = supplierService.getAllSuppliers();
        Stream<Supplier> tmp = list.stream();
        if(!supplierName.isEmpty()){
            tmp = tmp.filter(l->l.getSupplierName().contains(supplierName));
        }
        
        model.addAttribute("supplierQuery", tmp.toList());
        return "supplier";
    }
    @PostMapping("/create")
    public String create(@RequestParam("newSupplierName") String newSupplierName, @RequestParam("newSupplierAddress") String newSupplierAddress,
                         @RequestParam("newSupplierContact") String newSupplierContact, HttpSession session, Model model){
        Supplier supplier = supplierService.getSupplierBySupplierName(newSupplierName);
        if(supplier!=null){
            model.addAttribute("createError", "该供应商已存在");
        }else {
            supplier = new Supplier();
            supplier.setSupplierName(newSupplierName);
            supplier.setPlace(newSupplierAddress);
            supplier.setPhone(newSupplierContact);
            supplierService.addSupplier(supplier);
        }
        List<Supplier> suppliers = supplierService.getAllSuppliers();
        session.setAttribute("suppliers", suppliers);
        return "supplier";
    }
    
    
}
